# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

import pymongo
import csv
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import redis


class CSVPipeline:
    def open_spider(self, spider):
        if spider.name == "quotes_allpage":
            self.start_id = 1
            self.f = open(f'{spider.name}.csv', 'w', newline='')
            self.writer = csv.writer(self.f)
            self.writer.writerow(['id', 'author', 'content', 'tags'])

    def process_item(self, item, spider):
        if spider.name == "quotes_allpage":
            self.start_id += 1
            self.writer.writerow([f'{self.start_id}', item['author'], item['content'], '|'.join(item['tags'])])
            return item

    def close_spider(self, spider):
        if spider.name == "quotes_allpage":
            self.f.close()


class MongoPipeline:
    def open_spider(self, spider):
        self.client = pymongo.MongoClient("mongodb://localhost:27017/")
        self.db = self.client["quotes"]
        self.collection = self.db["quotes"]

    def process_item(self, item, spider):
        self.collection.insert_one(item)
        return item

    def close_spider(self, spider):
        self.client.close()


class ProducerPipeline:
    def open_spider(self, spider):
        if spider.name == "producer":
            self.client = redis.Redis()
            self.client.delete("tasks")

    def process_item(self, item, spider):
        if spider.name == "producer":
            self.client.lpush("tasks", json.dumps({
                'url': 'http://httpbin.org/post',
                'meta': item,
                'method': 'POST'
            }, ensure_ascii=False))
        return item

    def close_spider(self, spider):
        if spider.name == "producer":
            self.client.close()




